<template>
  <Dialog
    v-model="dialogVisible"
    :appendToBody="true"
    :title="spu.name ? '选择' + spu.name + '的规格' : '选择规格'"
  >
    <el-table v-loading="loading" :data="spu.skus" show-overflow-tooltip @row-click="onRowClick">
      <el-table-column label="#" width="55">
        <template #default="{ row }">
          <el-radio :value="row.id" v-model="selectedSkuId" @change="handleSelected(row)"
            >&nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column label="图片" min-width="80">
        <template #default="{ row }">
          <el-image
            :src="row.picUrl"
            class="h-30px w-30px"
            :preview-src-list="[row.picUrl]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="规格" align="center" min-width="80">
        <template #default="{ row }">
          {{ row.properties?.map((p) => p.valueName)?.join(' ') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售价(元)" min-width="80">
        <template #default="{ row }">
          {{ fenToYuan(row.price) }}
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ElTable } from 'element-plus'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { fenToYuan } from '@/utils'

defineOptions({ name: 'SkuTableSelect' })

const props = defineProps({
  spuId: {
    type: [Number, String],
    default: 0
  }
})

const spu = ref<any>({})
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示

const selectedSkuId = ref() // 选中的产品 spuId

/** 选中时触发 */
const handleSelected = (row: ProductSpuApi.Sku) => {
  emits('change', row)
  // 关闭弹窗
  dialogVisible.value = false
  selectedSkuId.value = undefined
}

const onRowClick = (row: ProductSpuApi.Sku) => {
  handleSelected(row)
}

// 确认选择时的触发事件
const emits = defineEmits<{
  (e: 'change', spu: ProductSpuApi.Sku): void
}>()

/** 打开弹窗 */
const open = (spuId: number | string) => {
  dialogVisible.value = true
  if (!spuId) {
    return
  }
  getSpuDetail(spuId)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getSpuDetail = async (spuId: number | string) => {
  loading.value = true
  try {
    spu.value = await ProductSpuApi.getSpu(spuId)
  } finally {
    loading.value = false
  }
}

/** 初始化 **/
onMounted(() => {})
watch(
  () => props.spuId,
  () => {
    if (!props.spuId) {
      return
    }
    getSpuDetail(props.spuId)
  }
)
</script>

<style lang="css" scoped>
:deep(.el-table__row) {
  cursor: pointer;
}
</style>
